//============================================================================
// TODO:
//    - log method writes to log file
//    - write to log file message priority (err, warn, dbg)
//    - rotate (backup old log file and create new if file is too large)
//    - [log component name]
//    - lockless, multiple threads can write to the same file simultaneously
//    - write time of event to log 
//    - [stack/call trace]
//
//       prototype: log(level, msg){}
//
//============================================================================
//class Logger{
//
//public void? log(int level, string msg){
//    
//}
//
//}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// MAIERS SINGLETONE
//
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <vector>
//#include "sorts.h"





class Logger {
    static Logger *_self;   
protected:
 
    Logger(){
        start = clock();
        fdLog = open("log.txt", O_RDWR|O_CREAT, 0666);
        write(fdLog, "Sorter release log\n", 20);
        numberOfFiles = 1;
        
    }
    ~Logger(){
        close(fdLog);
    }
    
public:
    
    static Logger& Instance() {
        static Logger theLog;
        return theLog;
    }
    

    
    
 
    void changeTheFile(){
        numberOfFiles++;
        char newName[5];
        unlink("log.txt");
        sprintf(newName, "%s%d%s","log",numberOfFiles,".txt");
        printf("%s",newName);
        rename("log", newName);
        close(fdLog);
        fdLog = open("log", O_RDWR|O_CREAT, 0666);
        
    }
    void msg(int level, const char messedge[]){
        int size = strlen(messedge);
        setTime();
        write(fdLog, timeParsed,12*sizeof(char));
        write(fdLog, " ", sizeof(char));
        write(fdLog, messedge, size);
        write(fdLog, "\n", sizeof(char));
    }
    
private:
    int fdLog;
    int numberOfFiles;
    char *buffer;
    clock_t start, middle;
    char timeParsed[12];
    void setTime(){
        middle = clock();
        double time = ((double) (middle - start)) / CLOCKS_PER_SEC;
        int hours = time/3600;
        int minutes = (time-3600*hours)/60;
        double seconds = time - hours * 3600 - minutes * 60;
        char _hours[3];
        if(hours<10)sprintf(_hours,"0%d",hours);
        else sprintf(_hours, "%d",hours);
        char _minutes[3];
        if(minutes<10)sprintf(_minutes,"0%d",minutes);
        else sprintf(_minutes, "%d",minutes);
        char _seconds[10];
        if(seconds<10)sprintf(_seconds,"0%f",seconds);
        else sprintf(_seconds, "%f",seconds);
        sprintf(timeParsed, "%s:%s:%s",_hours,_minutes,_seconds);
    }
    
    
};



